package com.example.stuwork.service.impl;

import com.example.stuwork.common.Result;
import com.example.stuwork.dao.StudentDao;
import com.example.stuwork.pojo.Student;
import com.example.stuwork.service.StudentService;
import com.example.stuwork.service.AssignmentAllocationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 学生服务实现类
 */
@Service
public class StudentServiceImpl implements StudentService {

    private static final Logger logger = LoggerFactory.getLogger(StudentServiceImpl.class);

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private AssignmentAllocationService assignmentAllocationService;

    /**
     * 获取所有学生
     *
     * @return 学生列表
     */
    @Override
    public Result<List<Student>> getAllStudents() {
        try {
            List<Student> students = studentDao.findAllStudents();
            // 不返回密码
            students.forEach(student -> student.setPassword(null));
            return Result.success(students);
        } catch (Exception e) {
            return Result.error("获取学生列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取学生信息
     *
     * @param studentId 学号
     * @return 学生信息
     */
    @Override
    public Result<Student> getStudentById(String studentId) {
        try {
            Student student = studentDao.findStudentById(studentId);
            if (student == null) {
                return Result.error("学生不存在");
            }
            // 不返回密码
            student.setPassword(null);
            return Result.success(student);
        } catch (Exception e) {
            return Result.error("获取学生信息失败：" + e.getMessage());
        }
    }

    /**
     * 添加学生
     *
     * @param student 学生信息
     * @return 结果
     */
    @Override
    public Result<?> addStudent(Student student) {
        try {
            // 检查学号是否已存在
            Student existingStudent = studentDao.findStudentById(student.getStudentId());
            if (existingStudent != null) {
                return Result.error("学号已存在");
            }

            int rows = studentDao.addStudent(student);
            if (rows > 0) {
                return Result.success("添加学生成功");
            } else {
                return Result.error("添加学生失败");
            }
        } catch (Exception e) {
            return Result.error("添加学生失败：" + e.getMessage());
        }
    }

    /**
     * 更新学生信息
     *
     * @param student 学生信息
     * @return 结果
     */
    @Override
    public Result<?> updateStudent(Student student) {
        try {
            // 检查学生是否存在
            Student existingStudent = studentDao.findStudentById(student.getStudentId());
            if (existingStudent == null) {
                return Result.error("学生不存在");
            }

            // 保持原密码不变
            student.setPassword(existingStudent.getPassword());
            
            // 检查班级ID是否更改
            Long newClassId = student.getClassId();
            Long oldClassId = existingStudent.getClassId();
            boolean classChanged = newClassId != null && 
                                 (oldClassId == null || !newClassId.equals(oldClassId));

            int rows = studentDao.updateStudent(student);
            if (rows > 0) {
                // 如果班级ID有变化，同步新班级的作业分配
                if (classChanged) {
                    Result<Boolean> syncResult = assignmentAllocationService.syncAssignmentsForNewStudent(
                        student.getStudentId(), newClassId);
                    if (!syncResult.isSuccess()) {
                        // 记录日志，但不影响学生信息更新结果
                        logger.warn("为学生{}同步新班级{}的作业分配失败: {}", 
                            student.getStudentId(), newClassId, syncResult.getMessage());
                    } else {
                        logger.info("已为学生{}同步新班级{}的作业分配", 
                            student.getStudentId(), newClassId);
                    }
                }
                return Result.success("更新学生信息成功");
            } else {
                return Result.error("更新学生信息失败");
            }
        } catch (Exception e) {
            return Result.error("更新学生信息失败：" + e.getMessage());
        }
    }

    /**
     * 删除学生
     *
     * @param studentId 学号
     * @return 结果
     */
    @Override
    public Result<?> deleteStudent(String studentId) {
        try {
            // 检查学生是否存在
            Student existingStudent = studentDao.findStudentById(studentId);
            if (existingStudent == null) {
                return Result.error("学生不存在");
            }

            int rows = studentDao.deleteStudent(studentId);
            if (rows > 0) {
                return Result.success("删除学生成功");
            } else {
                return Result.error("删除学生失败");
            }
        } catch (Exception e) {
            return Result.error("删除学生失败：" + e.getMessage());
        }
    }

    /**
     * 修改密码
     *
     * @param studentId    学号
     * @param oldPassword  旧密码
     * @param newPassword  新密码
     * @return 结果
     */
    @Override
    public Result<?> changePassword(String studentId, String oldPassword, String newPassword) {
        try {
            // 检查学生是否存在
            Student student = studentDao.findStudentById(studentId);
            if (student == null) {
                return Result.error("学生不存在");
            }

            // 验证旧密码
            if (!oldPassword.equals(student.getPassword())) {
                return Result.error("旧密码错误");
            }

            int rows = studentDao.updatePassword(studentId, newPassword);
            if (rows > 0) {
                return Result.success("修改密码成功");
            } else {
                return Result.error("修改密码失败");
            }
        } catch (Exception e) {
            return Result.error("修改密码失败：" + e.getMessage());
        }
    }

    /**
     * 按班级ID获取学生
     *
     * @param classId 班级ID
     * @return 学生列表
     */
    @Override
    public Result<List<Student>> getStudentsByClassId(Long classId) {
        try {
            List<Student> students = studentDao.findStudentsByClassId(classId);
            // 不返回密码
            students.forEach(student -> student.setPassword(null));
            return Result.success(students);
        } catch (Exception e) {
            return Result.error("获取班级学生失败：" + e.getMessage());
        }
    }

    /**
     * 按院系编号获取学生
     *
     * @param deptNumber 院系编号
     * @return 学生列表
     */
    @Override
    public Result<List<Student>> getStudentsByDeptNumber(String deptNumber) {
        try {
            List<Student> students = studentDao.findStudentsByDeptNumber(deptNumber);
            // 不返回密码
            students.forEach(student -> student.setPassword(null));
            return Result.success(students);
        } catch (Exception e) {
            return Result.error("获取院系学生失败：" + e.getMessage());
        }
    }

    /**
     * 按入学年份获取学生
     *
     * @param year 入学年份
     * @return 学生列表
     */
    @Override
    public Result<List<Student>> getStudentsByYear(String year) {
        try {
            List<Student> students = studentDao.findStudentsByYear(year);
            // 不返回密码
            students.forEach(student -> student.setPassword(null));
            return Result.success(students);
        } catch (Exception e) {
            return Result.error("获取年份学生失败：" + e.getMessage());
        }
    }

    /**
     * 按专业编码获取学生
     *
     * @param majorCode 专业编码
     * @return 学生列表
     */
    @Override
    public Result<List<Student>> getStudentsByMajorCode(String majorCode) {
        try {
            List<Student> students = studentDao.findStudentsByMajorCode(majorCode);
            // 不返回密码
            students.forEach(student -> student.setPassword(null));
            return Result.success(students);
        } catch (Exception e) {
            return Result.error("获取专业学生失败：" + e.getMessage());
        }
    }

    /**
     * 按课程ID获取学生
     *
     * @param courseId 课程ID
     * @return 学生列表
     */
    @Override
    public Result<List<Student>> getStudentsByCourseId(Long courseId) {
        try {
            List<Student> students = studentDao.findStudentsByCourseId(courseId);
            // 不返回密码
            students.forEach(student -> student.setPassword(null));
            return Result.success(students);
        } catch (Exception e) {
            return Result.error("获取课程学生失败：" + e.getMessage());
        }
    }

    /**
     * 搜索学生
     *
     * @param keyword 关键字
     * @return 学生列表
     */
    @Override
    public Result<List<Student>> searchStudents(String keyword) {
        try {
            List<Student> students = studentDao.searchStudents(keyword);
            // 不返回密码
            students.forEach(student -> student.setPassword(null));
            return Result.success(students);
        } catch (Exception e) {
            return Result.error("搜索学生失败：" + e.getMessage());
        }
    }

    /**
     * 获取班级学生数量
     *
     * @param classId 班级ID
     * @return 学生数量
     */
    @Override
    public Result<Integer> getStudentCountByClassId(Long classId) {
        try {
            List<Student> students = studentDao.findStudentsByClassId(classId);
            return Result.success(students.size());
        } catch (Exception e) {
            return Result.error("获取班级学生数量失败：" + e.getMessage());
        }
    }
} 